import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Divider,
  Tabs,
  Form,
  Icon,
  Modal,
  Table,
  Input,
  Upload,
  Select,
  Button,
  message,
  Popconfirm,
  Switch,
  DatePicker,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import TableComponent from 'components/TableComponent';
import StageEdit from 'components/StageEdit';
import token from '../../utils/token';

import styles from './index.less';

const { Option } = Select;
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const {  RangePicker} = DatePicker;

@connect(({ stageConfig, loading }) => ({
  stageConfig,
  loading: loading.models.stageConfig,
}))
@Form.create()
export default class StageConfig extends PureComponent {
  state = {
    modalVisible: false,
    stageSelect:[
      {
        tit:'已显示',
        val:'open',
      },
      {
        tit:'已隐藏',
        val:'close',
      },

    ],
    deviceSelect:[
      {
        tit:'android',
        val:'android',
      },
      {
        tit:'ios',
        val:'ios',
      },
    ],
    auditSelect:[
      {
        tit:'关闭',
        val:0,
      },
      {
        tit:'开启',
        val:1,
      },
    ],
    updateSelect:[
      {
        tit:'选更',
        val:0,
      },
      {
        tit:'强更',
        val:1,
      },
    ],
    statusSelect:[
      {
        tit: '屏蔽',
        val: 'close',
      },
      {
        tit: '开启',
        val: 'open',
      },
    ],
    senListParam:{
      mobileType: '',
      version: '',
      status: '',
      source: 'up',
      createTimeStart: '',
      createTimeEnd: '',
      audit:'',
      updateMust: '',
      channel: '',
      installmentStatus: '',
      current:1,
      pageSize: 10,
    },
    isEdit: false,
    editCon:{}
  };
  componentWillMount() {
    const { senListParam } = this.state;
    switch(this.props.location.pathname.split('/')[1]) {
      case 'operatingCenter':
        senListParam.source = 'up';
        break;
      case 'operatingCenterForXbeauty':
        senListParam.source = 'xbeauty';
        break;
      case 'operatingCenterForXflower':
        senListParam.source = 'xflower';
        break;
      case 'operatingCenterForUpoint':
        senListParam.source = 'upoint';
        break;
      default:
        break;
    }
  }

  componentDidMount() {
    this.initGetVersionList()
  }

  initGetVersionList = ()=>{
    const { dispatch } = this.props;
    const {senListParam} = this.state
    dispatch({
      type: 'stageConfig/fetchGetVersionList',
      payload:{
        ...senListParam
      }
    });
    dispatch({
      type: 'stageConfig/fetchGetChannelAndVersionQuery',
      payload:{
        ...{source: senListParam.source}
      }
    });
  }
  handleChangeStage =(text,record) =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'stageConfig/fetchUpdateInstallmentStatus',
      payload:{
        ...{id: record.id,installmentStatus:text=='open'? 'close': 'open'}
      },
      callback: ()=>{
        this.initGetVersionList();
      }
    });

  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { senListParam } = this.state;
    senListParam.current=  pagination.current;
    senListParam.pageSize = pagination.pageSize;
    this.initGetVersionList();
  };
  handleModal =(e)=>{
    this.setState({
      modalVisible: !!e,
    })
    if(!e){
      this.setState({
        editCon: {},
        isEdit: false,
      })
    }
  }
  handleEditVersion = (record)=>{
    this.setState({
      editCon: record,
      isEdit: true,
    })
    this.handleModal(true);
    console.log(record)
  }

  handleCreateTime =(dates,dateStrings,string) =>{
    this.state.senListParam.createTimeStart =dateStrings[0]? moment(dateStrings[0]).format('YYYY-MM-DD'): ''
    this.state.senListParam.createTimeEnd = dateStrings[1]? moment(dateStrings[1]).format('YYYY-MM-DD'): '';
  }
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    const {senListParam} = this.state;
    senListParam.mobileType = '' ;
    senListParam.version = '';
    senListParam.status = '';
    senListParam.audit = '';
    senListParam.channel = '';
    senListParam.installmentStatus =  '';
    senListParam.updateMust = '';
    senListParam.createTimeStart='';
    senListParam.createTimeEnd='';
    this.initGetVersionList();

  };
  handleSearch = e => {
    e.preventDefault();
    const { senListParam } = this.state
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log(fieldsValue)
      senListParam.mobileType = fieldsValue.mobileType? fieldsValue.mobileType: '' ;
      senListParam.version = fieldsValue.version? fieldsValue.version:'';
      senListParam.status = fieldsValue.status? fieldsValue.status:'';
      senListParam.audit = fieldsValue.audit? fieldsValue.audit:'';
      senListParam.channel = fieldsValue.channel? fieldsValue.channel: '';
      senListParam.installmentStatus = fieldsValue.installmentStatus?  fieldsValue.installmentStatus: '';
      senListParam.updateMust = fieldsValue.updateMust? fieldsValue.updateMust: '';
      this.initGetVersionList();
    });
  };
  renderRowClass = (record,index) =>{
      return record.deleteStatus == 1 ? styles.disabled:''
  }

  handleUpdateVersion = (e) =>{
    console.log(e)
    const { dispatch } = this.props;
    dispatch({
      type: 'stageConfig/fetchUpdateVersion',
      payload:{
        ...e
      },
      callback: (res)=>{
        const { dispatch } = this.props;
        const {senListParam} = this.state
        dispatch({
          type: 'stageConfig/fetchGetVersionList',
          payload:{
            ...senListParam
          }
        });
        this.handleModal(false);
        message.success(res.message)
      }
    });
  }
  handleAddVersion = (e) =>{
    console.log(e)
    const { dispatch,senListParam } = this.props;

    dispatch({
      type: 'stageConfig/fetchAddVersion',
      payload:{
        ...e
      },
      callback: (res)=>{
        const { dispatch } = this.props;
        const {senListParam} = this.state
        dispatch({
          type: 'stageConfig/fetchGetVersionList',
          payload:{
            ...senListParam
          }
        });
        this.handleModal(false);
        message.success(res.message)
      }
    });
  }

  renderForm(){
    const {form,stageConfig:{versionListData,channelVersionMap},loading} = this.props
    const { getFieldDecorator } = form;
    const {updateSelect,auditSelect,deviceSelect,stageSelect} =this.state
    return(
      <Card bordered={false} style={{marginBottom:20}}>
        <div style={{marginBottom:20}}> <Button type="primary" icon="plus" onClick={()=>{this.handleModal(true)}}>新建版本</Button></div>
        <Form onSubmit={this.handleSearch} >
          <Row style={{marginBottom:12}}  gutter={{ md: 12, lg:24, xl: 48 }}>
            <Col md={6} sm={24}>
              <FormItem label="设备类型">
                {getFieldDecorator('mobileType')(<Select >
                  {
                    deviceSelect.map((item,i)=>{
                      return  <Option value={item.val} key={i}>{item.tit}</Option>
                    })
                  }
                </Select>)}
              </FormItem>
            </Col>
            <Col md={6} sm={24}>
              <FormItem label="版本号">
                {getFieldDecorator('version')(<Select >
                  {
                    !loading ?
                      channelVersionMap.versionList.map((item,i)=>{
                        return  <Option value={item} key={i}>{item}</Option>
                      })
                      :''
                  }
                </Select>)}
              </FormItem>
            </Col>
            <Col md={6} sm={24}>
              <FormItem label="提审开关">
                {getFieldDecorator('audit')( <Select >
                  {
                    auditSelect.map((item,i)=>{
                      return  <Option value={item.val} key={i}>{item.tit}</Option>
                    })
                  }
                </Select>)}
              </FormItem>
            </Col>
            <Col md={6} sm={24}>
              <FormItem label="渠道">
                {getFieldDecorator('channel')(<Select >
                  {
                    !loading ?
                      channelVersionMap.channelList.map((item,i)=>{
                        return  <Option value={item} key={i}>{item}</Option>
                      })
                      :''
                  }
                </Select>)}
              </FormItem>
            </Col>
          </Row>
          <Row style={{marginBottom:12}}  gutter={{ md: 12, lg:24, xl: 48 }}>

            <Col md={6} sm={24}>
              <FormItem label="分期状态显示">
                {getFieldDecorator('installmentStatus')( <Select >
                  {
                    stageSelect.map((item,i)=>{
                      return  <Option value={item.val} key={i}>{item.tit}</Option>
                    })
                  }
                </Select>)}
              </FormItem>
            </Col>
            <Col md={6} sm={24}>
              <FormItem label="是否强更">
                {getFieldDecorator('updateMust')(<Select >
                  {
                    updateSelect.map((item,i)=>{
                      return  <Option value={item.val} key={i}>{item.tit}</Option>
                    })
                  }
                </Select>)}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <FormItem label="创建时间">
                {getFieldDecorator('createTime')(<RangePicker onChange={this.handleCreateTime} />)}
              </FormItem>
            </Col>

          </Row>
          <Row style={{marginBottom:12}}>
            <Col md={8} sm={24}>
              <Button type="primary" htmlType="submit" >
                查询
              </Button>
              <Button style={{marginLeft:18}} type="primary" onClick={this.handleFormReset}>
                重置
              </Button>
            </Col>

          </Row>

        </Form>
      </Card>
    )

  }


  render() {
    const {modalVisible,stageSelect,deviceSelect,auditSelect,updateSelect,isEdit,editCon,senListParam,statusSelect} = this.state;
    const {stageConfig:{versionListData},loading} = this.props
    const columns =[
      {
        title: '序号',
        key: 'sortNo',
        dataIndex: 'mobileType',
        render: (text, record,index) => (
          <a  href="javascript:;" >{index+1}</a>
        )
      },
      {
        title: '设备类型',
        dataIndex: 'mobileType',
        render: val => `${val}`
      },
      {
        title: '版本号',
        dataIndex: 'version',
        render: val => `${val}`
      },
      {
        title: '借款屏蔽状态',
        dataIndex: 'status',
        render: val => <span>{val=='open' ? '已开启': '已屏蔽'}</span>
      },
      {
        title: 'AppId',
        dataIndex: 'appId',
        render: val => val ?  `${val}` : '--',
      },
      {
        title: '提审开关',
        dataIndex: 'audit',
        render: val =><span>{val==0 ?'关闭':'开启'}</span>
      },
      {
        title: '更新内容',
        dataIndex: 'updateContent',
        render: val => `${val}`
      },
      {
        title: '是否需要强更',
        dataIndex: 'updateMust',
        render: val => val==0 ?'选更': '强更'
      },
      {
        title: '渠道',
        dataIndex: 'channel',
        render: val => `${val}`
      },
      {
        title: 'URL',
        dataIndex: 'downloadUrl',
        width: 200,
        render: val => `${val}`
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        render: val =><span>{moment(val).format('YYYY-MM-DD')}</span>
      },
      {
        title: '分期状态',
        dataIndex: 'installmentStatus',
        key: 'installmentStatus',
        render: (text, record) =>
        <div>
          <span style={{paddingRight:10}}>{text==='open' ? '已显示': '已隐藏'}</span>
          <Switch
            disabled={record.deleteStatus === 1}
            defaultChecked = {text==='open' ? true : false}
            onChange ={()=>{this.handleChangeStage(text,record)} }
          />
        </div>

      },

      {
        title: '操作',
        dataIndex: 'id',
        key:'id',
        render: (text, record) =>  <div>
          {
            record.deleteStatus == 1 ? '已下线' :
              <span>
                <a href="javascript:;" onClick={()=>{this.handleEditVersion(record)}}>编辑</a>

              </span>
          }

        </div>
      },
    ];

    return (
      <PageHeaderLayout title="版本显示">
        <div>{this.renderForm()}</div>
        <Card bordered={false}>
         <TableComponent
            data={versionListData}
            columns={columns}
            loading={loading}
            onChange={this.handleStandardTableChange}
            renderRowClass = {this.renderRowClass}
          />

        </Card>

        <Modal
          visible={modalVisible}
          onCancel={()=>{this.handleModal(false)}}
          footer={null}
          closable = {false}
        >
          <StageEdit
            stageSelect= {stageSelect}
            deviceSelect= {deviceSelect}
            auditSelect= {auditSelect}
            updateSelect= {updateSelect}
            isEdit = {isEdit}
            editCon = {editCon}
            addVersion={this.handleAddVersion}
            updateVersion={this.handleUpdateVersion}
            handleModal = {this.handleModal}
            source = {senListParam.source}
            statusSelect = {statusSelect}
          />

        </Modal>
      </PageHeaderLayout>
    );
  }
}
